<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/14
 * Time: 9:23
 */
//判断是否已登入，true:登入；false:未登入
function getLoginStatus()
{
    session_start();
    $Token = $_COOKIE["Token"];
    if (empty($Token)) {
        return false;
    }
    if (empty($_SESSION[$Token])) {
        return false;
    }
    return true;
}

//存钱函数
function moneyIn($CardId, $money)
{
    DbTools::InitDb();
    //加钱
    $sql = "update bankcard set CardMoney= CardMoney+$money where CardId=" . $CardId;
    $result = DbTools::noSelect($sql);
    if (!$result['status']) {
        DbTools::close();
        return $result;
    }
    //添加记录
    $sql = "insert into cardexchange(CardId,MoneyInBank,MoneyOutBank,ExchangeTime) 
          values($CardId,$money,0,NOW())";
    $result = DbTools::noSelect($sql);
    //关闭连接
    DbTools::close();
    //返回结果
    return $result;
}

//存取钱函数
//$type=1存钱 2取钱
function moneyInOut($type, $CardId, $money)
{
    $in_money = 0;
    $out_money = 0;
    $real_money = $money;
    if ($type == 1) {
        $in_money = $money;
    } else {
        $out_money = $money;
        $real_money = -$real_money;
    }
    DbTools::InitDb();
    //加减钱
    $sql = "update bankcard set CardMoney= CardMoney+$real_money where CardId=" . $CardId;
    if ($type == 2) {
        $sql .= " and CardMoney>=$money";
    }
    $result = DbTools::noSelect($sql);
    if (!$result['status']) {
        DbTools::close();
        return $result;
    }
    //添加记录
    $sql = "insert into cardexchange(CardId,MoneyInBank,MoneyOutBank,ExchangeTime) 
          values($CardId,$in_money,$out_money,NOW())";
    $result = DbTools::noSelect($sql);
    //关闭连接
    DbTools::close();
    //返回结果
    return $result;
}

//转账
function transferMoney($OutCardId, $InCardId, $money, $type = 0)
{
    if ($type == 0) {
        DbTools::InitDb();
    }
    //减钱
    $sql = "update bankcard set CardMoney= CardMoney-$money where CardId=$OutCardId and CardMoney>=$money";
    $result = DbTools::noSelect($sql);
    if (!$result['status']) {
        if ($type == 0) {
            DbTools::close();
        }
        return $result;
    }
    //加钱
    $sql = "update bankcard set CardMoney= CardMoney+$money where CardId=$InCardId";
    $result = DbTools::noSelect($sql);
    if (!$result['status']) {
        if ($type == 0) {
            DbTools::close();
        }
        return $result;
    }

    //添加记录
    $sql = "insert into cardtransfer(CardIdOut,CardIdIn,TransferMoney,TransferTime) 
          values($OutCardId,$InCardId,$money,NOW())";
    $result = DbTools::noSelect($sql);
    //关闭连接
    if ($type == 0) {
        DbTools::close();
    }
    return $result;
}

//根据卡号获取卡ID
function getCardIdByCardNo($cardNo)
{
    DbTools::InitDb();
    $sql = "select CardId from bankcard where CardNo=" . $cardNo;
    $result = DbTools::Select($sql);
    DbTools::close();
    if (!empty($result)) {
        return $result[0]['CardId'];
    }
    return 0;
}